package ilearn.job.ilearnjobgrayversionjava17.order.controller;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Log4j2
@RestController
@RefreshScope
public class OrderController {

    @Value(value = "#{'${versions:}'.split(',')}")
    private List<String> versions ;
    @Value(value = "${defaultVersion:}")
    private String defaultVersion;

    @GetMapping("/getOrderInfo")
    public String getOrderInfo(@RequestParam("userId")String userId,
                               @RequestHeader(value = "version",required = false,defaultValue = "")String versionHeader,
                               @RequestParam(value = "version",required = false)String versionParm,
                               @CookieValue(value = "version",required = false)String versionCookie){
       log.info("收到用户：{} 请求，版本号：versionHeader={}  versionParm={} versionCookie={}",
               userId,versionHeader,versionParm,versionCookie);
       if(StringUtils.hasText(versionHeader)){
           return exeRequestForVersion(userId,versionHeader);
       }else if(StringUtils.hasText(versionParm)){
           return exeRequestForVersion(userId,versionParm);
       }else {
           return exeRequestForVersion(userId,versionCookie);
       }
    }

    @GetMapping("/v={version}/getOrderInfo")
    public String getOrderInfoPathVersion(@RequestParam("userId")String userId,
                               @PathVariable(value = "version",required = false)String versionPath){
        log.info("收到用户：{} 请求，版本号：versionPath={} ",
                userId,versionPath);
        return exeRequestForVersion(userId,versionPath);
    }


    private String exeRequestForVersion(String userId,String version){
        if (StringUtils.hasText(version)){
            log.info("当前可用版本:{}",versions);
            if(!versions.contains(version)){
                throw new RuntimeException("版本:"+version + "已不支持");
            }
        }
        return String.format("已执行用户: %s的请求, 执行版本：%s 请求",userId,version);
    }

    @ExceptionHandler({RuntimeException.class})
    @ResponseStatus()
    public String runtimeExceptionHandler(RuntimeException runtimeException){
        return runtimeException.getLocalizedMessage();
    }

}
